import torch
import torch.nn as nn
import torch.nn.functional as F
from nets.custom_loss import my_loss
from layers.gat_layer import GATLayer
from layers.mlp_readout_layer import MLPReadout

"""
    GAT: Graph Attention Network
    Graph Attention Networks (Veličković et al., ICLR 2018)
    https://arxiv.org/abs/1710.10903
"""


class GATNet(nn.Module):

    def __init__(self, net_params):
        super().__init__()

        in_dim = net_params.in_dim_node
        in_dim_loop = net_params.in_dim_loop
        hidden_dim = net_params.hidden_dim
        out_dim = net_params.out_dim
        n_classes = net_params.n_classes
        num_heads = net_params.n_heads
        in_feat_dropout = net_params.in_feat_dropout
        dropout = net_params.dropout
        n_layers = net_params.n_layers

        self.readout = net_params.readout
        self.batch_norm = net_params.batch_norm
        self.residual = net_params.residual
        self.dropout = dropout
        self.n_classes = n_classes
        self.device = net_params.device
        self.pos_enc = net_params.pos_enc
        self.pos_enc_dim = net_params.pos_enc_dim
        self.add_loop_type = net_params.add_loop_type
        self.loss_type = net_params.loss_type

        self.embedding_h = nn.Embedding(in_dim, hidden_dim * num_heads)
        self.embedding_loop = nn.Embedding(in_dim_loop, hidden_dim * num_heads)

        self.in_feat_dropout = nn.Dropout(in_feat_dropout)

        if self.pos_enc == True:
            self.embedding_pos_enc = nn.Linear(self.pos_enc_dim, hidden_dim * num_heads)

        self.layers = nn.ModuleList([GATLayer(hidden_dim * num_heads, hidden_dim, num_heads,
                                              dropout, self.batch_norm, self.residual) for _ in range(n_layers - 1)])
        self.layers.append(GATLayer(hidden_dim * num_heads, out_dim, 1, dropout, self.batch_norm, self.residual))
        self.MLP_layer = MLPReadout(out_dim, n_classes)

    def forward(self, g, h, e, loop_type=None, h_pos_enc=None):
        # input embedding
        h = self.embedding_h(h)
        h = self.in_feat_dropout(h)

        if self.add_loop_type:  # 是否使用loop_type特征
            loop_type = self.embedding_loop(loop_type)
            h = h + loop_type

        if self.pos_enc:  # 是否使用位置编码
            h_pos_enc = self.embedding_pos_enc(h_pos_enc.float())
            h = h + h_pos_enc

        # GAT conv
        for conv in self.layers:
            h = conv(g, h)

        # output
        h_out = self.MLP_layer(h)

        return h_out

    def loss(self, pred, label, mask):
        loss = my_loss(pred, label, mask, self.loss_type)
        return loss
